import { Col, Row, Divider, Button, Checkbox, Form, Input, message, Spin } from 'antd'
import { UserOutlined, LockOutlined } from '@ant-design/icons'
import { getNameAndPas, setNameAndPas, removeNameAndPas, setToken } from '@/utils/auth'
import { useEffect, useState } from 'react'
import { Login } from '@/api/user'
import { useNavigate } from 'react-router-dom'
interface userInfo {
  username: string
  password: string
  remember: boolean
}
import './index.css'
function App() {
  const nav = useNavigate()
  const [loading, setLoading] = useState(false)

  const [form] = Form.useForm()
  useEffect(() => {
    let data: userInfo = getNameAndPas()
    if (data) {
      const { username, password } = data
      form.setFieldsValue({ username, password })
    }
  }, [])
  const onFinish = (values: userInfo) => {
    setLoading(true)
    const { username, password, remember } = values
    Login({ username, password })
      .then(res => {
        if (res.status === 200) {
          setLoading(false)
          message.success('登录成功')
          setToken(res.data.token)
          nav('/')
          if (remember) {
            setNameAndPas(values)
          } else {
            removeNameAndPas()
          }
        } else {
          setLoading(false)
          message.error(res.data)
        }
      })
      .catch(err => {
        setLoading(false)
        message.error(err)
      })
  }
  const onFinishFailed = () => {}
  return (
    <div className='login'>
      {loading && <Spin className='spin login-spin' size='large' />}
      <Row style={{ height: '100%' }}>
        <Col span={16} className='login-left'>
          <h2>欢迎光临</h2>
          <p style={{ fontSize: '20px' }}>React18 + Ts 实战商城后台管理系统开发</p>
        </Col>
        <Col span={8} className='login-right' style={{ textAlign: 'center' }}>
          <h1>欢迎回来</h1>
          <Divider>账号密码登录</Divider>
          <Form
            name='basic'
            initialValues={{ remember: true }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete='off'
            form={form}
            className='login-form'
          >
            <Form.Item label='账号' name='username' rules={[{ required: true, message: '请输入用户名！' }]}>
              <Input prefix={<UserOutlined />} />
            </Form.Item>

            <Form.Item label='密码' name='password' rules={[{ required: true, message: '请输入密码' }]}>
              <Input.Password prefix={<LockOutlined />} />
            </Form.Item>

            <Form.Item name='remember' valuePropName='checked'>
              <Checkbox>记住我</Checkbox>
            </Form.Item>

            <Form.Item>
              <Button type='primary' htmlType='submit'>
                登录
              </Button>
            </Form.Item>
          </Form>
        </Col>
      </Row>
    </div>
  )
}

export default App
